import React, { useState, useEffect } from 'react';
import { useParams, Link } from 'react-router-dom';
import { Card, Descriptions, Avatar, Spin, Button, message } from 'antd';
import apiService from '../services/apiService';

const UserDetail = () => {
  const { id } = useParams();
  const [user, setUser] = useState(null);
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    const fetchUserDetail = async () => {
      setLoading(true);
      try {
        const response = await apiService.getUser(id);
        if (response && response.User) {
          setUser(response.User);
        }
      } catch (error) {
        message.error('获取用户详情失败');
      } finally {
        setLoading(false);
      }
    };

    if (id) {
      fetchUserDetail();
    }
  }, [id]);

  // 解析JSON字符串为数组
  const parseJsonArray = (jsonStr) => {
    try {
      if (!jsonStr) return [];
      return JSON.parse(jsonStr);
    } catch (error) {
      return [];
    }
  };

  return (
    <Card 
      title="用户详情" 
      extra={
        <Button type="primary">
          <Link to="/users">返回列表</Link>
        </Button>
      }
    >
      <Spin spinning={loading}>
        {user ? (
          <div>
            <div style={{ textAlign: 'center', marginBottom: 20 }}>
              <Avatar size={100} src={user.head} />
              <h2 style={{ marginTop: 10 }}>{user.name}</h2>
            </div>
            
            <Descriptions bordered>
              <Descriptions.Item label="ID">{user.id}</Descriptions.Item>
              <Descriptions.Item label="性别">{user.sex === 0 ? '男' : '女'}</Descriptions.Item>
              <Descriptions.Item label="标签">{user.tag}</Descriptions.Item>
              <Descriptions.Item label="注册日期">{new Date(user.date).toLocaleString()}</Descriptions.Item>
            </Descriptions>
            
            <Card title="图片列表" style={{ marginTop: 20 }}>
              {parseJsonArray(user.pictureList).map((pic, index) => (
                <img 
                  key={index} 
                  src={pic} 
                  alt={`用户图片${index}`} 
                  style={{ width: 100, height: 100, margin: 10, objectFit: 'cover' }} 
                />
              ))}
            </Card>
            
            <Card title="联系人ID列表" style={{ marginTop: 20 }}>
              {parseJsonArray(user.contactIdList).join(', ')}
            </Card>
          </div>
        ) : !loading && (
          <div style={{ textAlign: 'center' }}>未找到用户信息</div>
        )}
      </Spin>
    </Card>
  );
};

export default UserDetail; 